import json
from .models import BackupRecords
from blueapps.account.decorators import login_exempt
from blueking_api.cmdb_api import BaseApi
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

api = BaseApi()


# Create your views here.
# 文件查找文件备份

# 开发框架中通过中间件默认是需要登录态的，如有不需要登录的，可添加装饰器login_exempt
# 装饰器引入 from blueapps.account.decorators import login_exempt
@login_exempt
def home(request):
    files = [{
        "id": i,
        "ip": "23.45.67.89",
        "file_list": "1.log;3.log.5.log",
        "file_num": 3,
        "file_size": i * 1000000} for i in range(10)]
    # 获取业务信息
    bizs = api.requests("POST", "search_business")
    biz_infos = bizs["data"]["info"] if bizs.get("result", False) else []
    return render(request, "resource_manager/index_home.html", {"files": files, "bizs": biz_infos})


def search_biz_inst_topo(request):
    params = json.loads(request.body)
    bk_biz_id = params.get("bk_biz_id", None)
    data = {}
    if bk_biz_id:
        # 查询业务实例拓扑
        res = api.requests("POST", "search_biz_inst_topo", {"bk_biz_id": bk_biz_id})
        if res['result'] == True:
            data = res['data'][0]
    return JsonResponse(data)


def backup_records(request):
    """备份操作记录"""
    try:
        params = json.loads(request.body)
        start = params("start", 0)
        length = params.get("length", 30)
    except:
        start, length = 0, 30
    page = start / length + 1
    records = BackupRecords.objects.all()
    paginator = Paginator(records, length)
    data = [item for item in paginator.get_page(page)]
    return render(request, "resource_manager/backup_records.html", {"data": data})
